<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button v-waves class="filter-item" type="primary" size="mini" icon="el-icon-plus" @click="handleAddWindow()">
        {{ $t('user_role.button.add') }}
      </el-button>
    </div>
    <el-table size="mini" v-loading="listLoading" :data="list" highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" width="50">
        <template slot-scope="{row}">
          <span>{{ row.Id }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" :label="$t('user_role.table.name')">
        <template slot-scope="{row}">
          <span>{{ row.Name }}</span>
        </template>
      </el-table-column>
      <el-table-column width="160px" align="center" :label="$t('user_role.table.sign')">
        <template slot-scope="{row}">
          <span>{{ row.Sign }}</span>
        </template>
      </el-table-column>
      <el-table-column width="200px" align="center" :label="$t('user_role.table.remark')">
        <template slot-scope="{row}">
          <span>{{ row.Mark }}</span>
        </template>
      </el-table-column>

      <el-table-column width="200px" :label="$t('user_role.table.created_at')" align="center">
        <template slot-scope="{row}">
          <span>{{ row.CreatedAt }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" :label="$t('user_role.table.state')"  align="center" width="100">
        <template slot-scope="{row}">
          <i class="el-icon-check" style="color: green" v-if="row.State"></i>
          <i class="el-icon-close" style="color: red" v-if="!row.State"></i>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="{row}">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleEditWindow(row)"
          >
            {{ $t('button.edit') }}
          </el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="handleEditPermissionDialog(row.Id)"
          >
            {{ $t('user_role.button.edit_acl') }}
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleStatus(row.Id)"
          >
            <span v-if="!row.State">{{ $t('button.enable') }}</span>
            <span v-if="row.State">{{ $t('button.disable') }}</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗  -->
    <el-dialog :title="dialogEditFormTitle === 'add' ? $t('user_role.window.add_window_title') : $t('user_role.window.edit_window_title') " :visible.sync="dialogEditFormVisible">
      <el-form ref="dataEditForm" :rules="rules" :model="editData" label-position="left" label-width="120px" style="width: 800px; margin-left:50px;">
        <el-form-item :label="$t('user_role.window.add_field_name')" prop="name">
          <el-input v-model="editData.name" style="width: 380px;" />
        </el-form-item>
        <el-form-item :label="$t('user_role.window.add_field_remark')" prop="mark">
          <el-input v-model="editData.mark" style="width: 380px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('button.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleEditCommit()">
          {{ $t('button.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 弹窗  -->
    <el-dialog :title="$t('user_role.window.edit_acl_window_title')" :visible.sync="dialogEditPermissionVisible">
      <el-form ref="dataPermissionForm" :rules="rules"  label-position="left" label-width="90px" style="width: 760px; margin-left:50px;">
        <el-tree
          :data="currentPermissions"
          show-checkbox
          node-key="id"
          accordion
          ref="permissionTree"
          :default-checked-keys="defaultCheckedPermissions"
          :props=" { children: 'children', label: 'label'}">
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('button.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleEditPermissionSubmit()">
          {{ $t('button.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 弹窗  -->
    <el-dialog :title="$t('user_role.window.edit_menu_window_title')" :visible.sync="dialogEditMenuVisible">
      <el-form ref="dataMenuForm" :rules="rules"  label-position="left" label-width="90px" style="width: 860px; margin-left:50px;">
        <el-tree
          :data="currentMenus"
          show-checkbox
          node-key="id"
          accordion
          ref="menuTree"
          :default-checked-keys="defaultCheckedMenus"
          :props=" { children: 'children', label: 'label'}">
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('button.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleEditMenuSubmit()">
          {{ $t('button.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { userRoleList, userRoleAdd, userRoleStatus, userRoleGetPermission, userRoleEditPermission } from '@/api/user'
import waves from '@/directive/waves'
import local from '@/lang/users/user_role'

export default {
  name: 'UserRoleList',
  directives: { waves },
  data() {
    return {
      list: null,
      listLoading: true,
      searchData: {
        page_index: 1,
        page_size: 15
      },
      dialogEditFormVisible: false,
      dialogEditFormTitle: 'edit',
      editData: {
        id: 0,
        name: '',
        mark: ''
      },

      dialogEditPermissionVisible: false,
      currentEditPermissionId: 0,
      currentPermissions: [],
      defaultCheckedPermissions: [],

      dialogEditMenuVisible: false,
      currentEditMenuId: 0,
      currentMenus: [],
      defaultCheckedMenus: [],
      rules: {
        name: [{ required: true, message: '需要填写角色名称', trigger: 'blur' }],
        mark: [{ required: true, message: '需要填写角色备注', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    if (!this.$i18n.getLocaleMessage('en')['user_role']) {
      this.$i18n.mergeLocaleMessage('en', local.en)
      this.$i18n.mergeLocaleMessage('zh', local.zh)
    }
  },
  methods: {
    T_tips(msg) {
      const hasKey = this.$te('user_role.tips.' + msg)
      if (hasKey) {
        const translatedMsg = this.$t('user_role.tips.' + msg)
        return translatedMsg
      }
      return msg
    },
    resetEditData() {
      this.addData = {
        id: 0,
        name: '',
        mark: ''
      }
    },
    getList() {
      this.listLoading = true
      userRoleList(this.searchData).then(response => {
        if (response.success) {
          this.list = response.data.data
          this.total = response.data.total
        } else {
          this.$message({
            type: 'error',
            message: response.msg
          })
        }

        setTimeout(() => {
          this.listLoading = false
        }, 200)
      }).catch(err => {
        this.$message({
          type: 'success',
          message: err
        })
      })
    },
    handleAddWindow() {
      this.dialogEditFormTitle = 'add'
      this.handleEditWindow({ name: '', mark: '', id: 0 })
    },
    handleEditWindow(item) {
      this.resetEditData()
      this.editData.id = item.Id
      this.editData.name = item.Name
      this.editData.mark = item.Mark
      this.dialogEditFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataEditForm'].clearValidate()
      })
    },
    handleEditCommit() {
      userRoleAdd(this.editData).then((response) => {
        if (response.success) {
          this.dialogEditFormVisible = false
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          this.getList()
        } else {
          this.$message({
            type: 'error',
            message: response.msg
          })
        }
      })
    },
    handleEditPermissionDialog(id) {
      this.dialogEditPermissionVisible = true
      this.currentEditPermissionId = id
      userRoleGetPermission(id).then((response) => {
        if (response.success) {
          this.currentPermissions = response.data.current_permissions
          this.defaultCheckedPermissions = response.data.checked_permissions
        }
      })
    },
    handleEditPermissionSubmit() {
      const permissions = this.getCheckedPermissionsKeys()
      userRoleEditPermission(this.currentEditPermissionId, permissions).then((response) => {
        if (response.success) {
          this.dialogEditPermissionVisible = false
          this.$message({
            type: 'success',
            message: '编辑权限成功!'
          })
        } else {
          this.$message({
            type: 'success',
            message: response.msg
          })
        }
      })
    },
    handleStatus(id) {
      this.$confirm('此操作将 禁用 / 启用 指定角色 (分配的用户将无法登陆), 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userRoleStatus(id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: '修改角色状态成功!'
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消禁用'
        })
      })
    },
    getCheckedMenuKeys() {
      return this.$refs.menuTree.getCheckedKeys()
    },
    getCheckedPermissionsKeys() {
      return this.$refs.permissionTree.getCheckedKeys()
    }
  }
}
</script>
